import json
from datetime import datetime

from PyQt6.QtNetwork import QUdpSocket, QTcpServer, QTcpSocket, QHostAddress

import GlobalData

udpsocket = QUdpSocket()
tcpfilesocket = QTcpSocket()
tcpfileserver = QTcpServer()
uport = 23233
uaddr = QHostAddress.SpecialAddress.Broadcast
tport = 5555


def init():
    # 从文件读取下一个端口和用户，用于同时开启多个客户端调试
    with open('clientid', 'r') as f:
        GlobalData.initClient(int(f.readline()))
    with open('clientid', 'w') as f:
        f.writelines([str(GlobalData.cid + 1), '\n'])

    udpsocket.bind(GlobalData.port, QUdpSocket.BindFlag.ShareAddress or QUdpSocket.BindFlag.ReuseAddressHint)


def setOnline(online):
    if online:
        datagram = createDatagram('Online')
    else:
        datagram = createDatagram('Offline')
    data = bytes(json.dumps(datagram), 'utf-8')
    udpsocket.writeDatagram(data, uaddr, uport)


def sendTextMessage(peer, message):
    data = createDatagram("Message", peer, message)
    data = bytes(json.dumps(data), 'utf-8')
    udpsocket.writeDatagram(data, uaddr, uport)


def beginSendFile(name, peer, size):
    data = createDatagram('Notif', peer, [name, size])
    data = bytes(json.dumps(data), 'utf-8')
    udpsocket.writeDatagram(data, uaddr, uport)


def downloadFile(name, sender):
    data = createDatagram('ReqFile', body=[name, sender])
    data = bytes(json.dumps(data), 'utf-8')
    udpsocket.writeDatagram(data, uaddr, uport)


def createDatagram(dtype, peer='', body: str | dict | list = ''):
    return {
        "Type": dtype,
        "Username": GlobalData.currentUser,
        "Peername": peer,
        "Body": body,
        "Datetime": str(datetime.now())
    }


def sendTcpMessage(host: QHostAddress, data):
    addr = QHostAddress(host.toString()[7:])
    tcpfilesocket.connectToHost(addr, tport)
    data = bytes(json.dumps(data), 'utf-8')
    tcpfilesocket.writeData(data)
